package com.honghe.aop;

import com.honghe.annotation.AutoFill;
import com.honghe.constant.AutoFillConstant;
import com.honghe.context.BaseContext;
import com.honghe.enumeration.OperationType;
import com.honghe.exception.BaseException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
public class AutoFillAspect {
    @Pointcut("execution(* com.honghe.mapper.*.*(..)) && @annotation(com.honghe.annotation.AutoFill)")//捕捉查询的切面
    public void  autoFill() {}
    @Before("autoFill()")
    public void doBefore(JoinPoint joinPoint){
        MethodSignature signature =(MethodSignature) joinPoint.getSignature();//获取方法签名对象
        AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);//获取捕捉到的方法上的注解对象
        OperationType value = annotation.value(); //获取到注解对象里的值
        Object[] args = joinPoint.getArgs();//获取被拦截的对象
        if (args==null || args.length==0){
            return;
        }
        Object arg = args[0];
        //准备赋值对象
        LocalDateTime now = LocalDateTime.now();
        Long id = BaseContext.getCurrentId();//医生id
        if (value == OperationType.INSERT){
            try {
                Method setCreateTime = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setUpdateTime = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setCreateUser = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                Method setUpdateUser = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                setCreateTime.invoke(arg,now);
                setUpdateTime.invoke(arg,now);
                setCreateUser.invoke(arg,id);
                setUpdateUser.invoke(arg,id);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else if (value == OperationType.UPDATE) {
            try {
                Method setUpdateTime = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                setUpdateTime.invoke(arg,now);
                setUpdateUser.invoke(arg,id);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }else {
            throw new BaseException("value值必须是OperationType枚举类型");
        }
    }
}
